[SQL] Getting the sum of several columns from two tables

Posted by romaintaz on Stack Overflow See other posts from Stack Overflow or by romaintaz
Published on 2009-09-07T08:32:26Z Indexed on 2010/05/19 14:50 UTC
Read the original article Hit count: 177

Filed under:
|
|
|

I want to get the sum of several columns from 2 different tables (these tables share the same structure).

If I only consider one table, I would write this kind of query:

SELECT MONTH_REF, SUM(amount1), SUM(amount2)
    FROM T_FOO
    WHERE seller = XXX
    GROUP BY MONTH_REF;

However, I would like to also work with the data from the table T_BAR, and then have a select query that return the following columns:

  • MONTH_REF
  • SUM(T_FOO.amount1) + SUM(T_BAR.amount1)
  • SUM(T_FOO.amount2) + SUM(T_BAR.amount2)

everything grouped by the value of MONTH_REF.

Note that a record for a given MONTH_REF can be found in one table but not in the other table. In this case, I would like to get the sum of T_FOO.amount1 + 0 (or 0 + T_BAR.amount1).

How can I write my SQL query to get this information?

For information, my database is Oracle 10g.

© Stack Overflow or respective owner

Related posts about sql

Related posts about Oracle